<template>
  <div class="register-container">
    <a-card class="register-card" title="注册">
      <a-form
        :model="formState"
        name="register"
        @finish="onFinish"
        :rules="rules"
      >
        <a-form-item name="firstName">
          <a-input v-model:value="formState.firstName" placeholder="请输入名字(First Name)">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="lastName">
          <a-input v-model:value="formState.lastName" placeholder="请输入姓氏(Last Name)">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="phone">
          <PhoneNumberInput @update:phoneData="handlePhoneData" />
        </a-form-item>

        <a-form-item name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱">
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="hasInviteCode">
          <a-checkbox v-model:checked="formState.hasInviteCode">我有邀请码</a-checkbox>
        </a-form-item>

        <a-form-item name="inviteCode" v-if="formState.hasInviteCode">
          <a-input v-model:value="formState.inviteCode" placeholder="请输入邀请码">
            <template #prefix>
              <GiftOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password">
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入密码"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="confirmPassword">
          <a-input-password
            v-model:value="formState.confirmPassword"
            placeholder="请确认密码"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="recaptcha">
          <GoogleRecaptcha 
            ref="recaptchaRef"
            :site-key="recaptchaSiteKey"
            @verified="handleRecaptchaVerified"
            @expired="handleRecaptchaExpired"
            @error="handleRecaptchaError"
          />
        </a-form-item>

        <a-form-item name="agreement">
          <a-checkbox v-model:checked="formState.agreement">
            我已阅读并同意 <a href="#" @click.prevent="showAgreement">用户协议</a> 和 <a href="#" @click.prevent="showPrivacyPolicy">隐私政策</a>
          </a-checkbox>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" block>注册</a-button>
        </a-form-item>

        <div class="form-footer">
          <router-link to="/login">已有账号？立即登录</router-link>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { UserOutlined, LockOutlined, MailOutlined, GiftOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import type { Rule } from 'ant-design-vue/es/form';
import PhoneNumberInput from '@/components/PhoneNumberInput.vue';
import GoogleRecaptcha from '@/components/GoogleRecaptcha.vue';

interface FormState {
  firstName: string;
  lastName: string;
  countryCode: string;
  phoneNumber: string;
  email: string;
  hasInviteCode: boolean;
  inviteCode: string;
  password: string;
  confirmPassword: string;
  agreement: boolean;
  recaptchaToken: string;
}

interface PhoneData {
  isValid: boolean;
  data: {
    countryCode: string;
    phoneNumber: string;
    fullNumber: string;
    isValid: boolean;
  };
}

const router = useRouter();
const route = useRoute();
const recaptchaRef = ref(null);
const recaptchaSiteKey = '6LflA-MqAAAAAChtyQ0Xsn337ycrybSGkHMEbPmw'; // 替换为您的实际站点密钥
const recaptchaVerified = ref(false);

const formState = reactive<FormState>({
  firstName: '',
  lastName: '',
  countryCode: '',
  phoneNumber: '',
  email: '',
  hasInviteCode: false,
  inviteCode: '',
  password: '',
  confirmPassword: '',
  agreement: false,
  recaptchaToken: '',
});

const phoneIsValid = reactive({ value: false });

const handlePhoneData = (data: PhoneData) => {
  if (data.isValid && data.data.isValid) {
    //打印数据
    // console.log(data.data.countryCode,data.data.phoneNumber,123123);
    formState.countryCode = data.data.countryCode;
    formState.phoneNumber = data.data.phoneNumber;
    phoneIsValid.value = true;
  } else {
    formState.countryCode = '';
    formState.phoneNumber = '';
    phoneIsValid.value = false;
  }
};

const handleRecaptchaVerified = (token: string) => {
  formState.recaptchaToken = token;
  recaptchaVerified.value = true;
  console.log('reCAPTCHA 验证成功，token:', token);
};

const handleRecaptchaExpired = () => {
  formState.recaptchaToken = '';
  recaptchaVerified.value = false;
};

const handleRecaptchaError = (error: any) => {
  console.error('reCAPTCHA error:', error);
  formState.recaptchaToken = '';
  recaptchaVerified.value = false;
};

const validateRecaptcha = async (_rule: Rule, _value: string) => {
  if (!recaptchaVerified.value || !formState.recaptchaToken) {
    return Promise.reject('Please complete the CAPTCHA verification');
  }
  return Promise.resolve();
};

const validatePassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请输入密码');
  }
  if (value.length < 8) {
    return Promise.reject('密码长度不能小于8位');
  }
  if (!/[A-Z]/.test(value)) {
    return Promise.reject('密码必须包含至少一个大写字母');
  }
  if (!/[a-z]/.test(value)) {
    return Promise.reject('密码必须包含至少一个小写字母');
  }
  if (!/\d/.test(value)) {
    return Promise.reject('密码必须包含至少一个数字');
  }
  return Promise.resolve();
};

const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请确认密码');
  }
  if (value !== formState.password) {
    return Promise.reject('两次输入的密码不一致');
  }
  return Promise.resolve();
};

const validateAgreement = async (_rule: Rule, value: boolean) => {
  if (!value) {
    return Promise.reject('请阅读并同意用户协议和隐私政策');
  }
  return Promise.resolve();
};
const validatePhone = async (_rule: Rule, _value: string) => {
  
  
  return Promise.resolve();
};

const rules: Record<string, Rule[]> = {
  firstName: [
    { required: true, message: '请输入名字', trigger: 'blur' }
  ],
  lastName: [
    { required: true, message: '请输入姓氏', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  inviteCode: [
    { required: false, message: '请输入邀请码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'change' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'change' }
  ],
  recaptcha: [
    { validator: validateRecaptcha, trigger: 'change' }
  ],
  agreement: [
    { validator: validateAgreement, trigger: 'change' }
  ]
};

const showAgreement = () => {
  message.info('用户协议内容');
};

const showPrivacyPolicy = () => {
  message.info('隐私政策内容');
};

const onFinish = async () => {
  try {
    // 检查人机验证是否通过
    if (!recaptchaVerified.value || !formState.recaptchaToken) {
      message.error('Please complete the CAPTCHA verification');
      return;
    }
    
    // 调用注册API
    const registerData = {
      firstName: formState.firstName,
      lastName: formState.lastName,
      countryCode: formState.countryCode,
      phoneNumber: formState.phoneNumber,
      email: formState.email,
      inviteCode: formState.hasInviteCode ? formState.inviteCode : undefined,
      password: formState.password,
      recaptchaToken: formState.recaptchaToken
    };
    
    // TODO: 调用注册API
    console.log('注册数据:', registerData);
    
    message.success('注册成功');
    router.push('/login');
  } catch (error) {
    message.error('注册失败');
  }
};

// 在组件挂载时从URL获取邀请码
onMounted(() => {
  // 从URL中获取邀请码参数
  const codeFromUrl = route.query.code;
  
  if (codeFromUrl && typeof codeFromUrl === 'string') {
    // 自动勾选"我有邀请码"
    formState.hasInviteCode = true;
    // 设置邀请码值
    formState.inviteCode = codeFromUrl;
    console.log('自动填写邀请码:', codeFromUrl);
  }
});
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 90vh;
  background: #f0f2f5;
}

.register-card {
  width: 100%;
  max-width: 400px;
}

.form-footer {
  text-align: right;
  margin-top: 16px;
}
</style> 